<?php

namespace app\services\order;

use app\model\finance\FinanceStatistic;
use app\model\order\StoreOrder;
use crmeb\exceptions\ApiException;
use think\facade\Db;

/**
 * 用来维护订单统计的服务类
 */
class OrderMoneyStatisticService
{
    /**
     * @param $order_id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function settleByOrderFinish($order_id)
    {
        $order = StoreOrder::with(['items'])->where('id', $order_id)->find();
        if (!$order) throw new ApiException(400118);

        Db::transaction(function () use ($order) {
            // 1. 添加 zg_finance_statistics 财务支出表
            FinanceStatistic::create([
                'order_id'  =>  $order->id,
                'sn'    =>  $order->sn,
                'trade_type'    =>  1,
                'user_id'   =>  $order->uid,
                'trade_time'    =>  $order->pay_time,
                'amount_type'   =>  1,
                'amount'    =>  $order->price
            ]);

            // 2. 如果是分销商品, 需要统计进 zg_agent_money_logs，zg_user_money 表
            // 遍历items, 发现有没有存在分销的商品
            foreach ($order->items() as $item) {
                // 判断是否参与分销
                if ($item->attrValue->join_agent == 1) {

                }
            }

        });
    }
}